package com.ysu.yybk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysu.yybk.VO.old.OldResultVO;
import com.ysu.yybk.entity.checkin.Checkin;
import com.ysu.yybk.entity.checkin.CheckinStudent;
import com.ysu.yybk.entity.course.Course;
import com.ysu.yybk.entity.course.CourseStudent;
import com.ysu.yybk.form.checkin.StudentSubmit;
import com.ysu.yybk.mapper.checkin.CheckinMapper;
import com.ysu.yybk.mapper.checkin.CheckinStudentMapper;
import com.ysu.yybk.mapper.course.CourseMapper;
import com.ysu.yybk.mapper.course.CourseStudentMapper;
import com.ysu.yybk.service.CheckinStudentService;
import com.ysu.yybk.util.ResultVOUtil;
import com.ysu.yybk.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author ：lhw
 * @date ：Created in 2019/11/18 22:00
 */
@Service
public class CheckinStudentServiceImpl implements CheckinStudentService {
    private static final Logger logger = LoggerFactory.getLogger(CheckinStudentServiceImpl.class);
    @Autowired
    CourseStudentMapper courseStudentMapper;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    CheckinMapper checkinMapper;

    @Autowired
    CheckinStudentMapper checkinStudentMapper;

    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    ObjectMapper objectMapper;

    @Override
    public Map<String, Object> getInfo(String studentId) {
        if(TimeUtil.getTime() == -1){
            Map<String,Object> result =  new HashMap<String, Object>();
            result.put("error_code",1);
            return result;
        }

        List<CourseStudent> courseStudents = courseStudentMapper.selectList(
                new QueryWrapper<CourseStudent>().eq("student_id",studentId)
        );

        //此人无课
        if(courseStudents.isEmpty()){
            Map<String,Object> result =  new HashMap<String, Object>();
            result.put("error_code",1);
            return result;
        }

        List<String> courses = new ArrayList<>();

        courseStudents.forEach(courseStudent -> {
            courses.add(courseStudent.getCourseId());
        });

//        List<Course> courseList = courseMapper.selectList(
//                new QueryWrapper<Course>().in("id",courses)
//                    .le("week_start", TimeUtil.getWeek())
//                    .ge("week_end",TimeUtil.getWeek())
//                    .eq("day",TimeUtil.getDate())
//                    .eq("time",TimeUtil.getTime())
//        );
//
//        if(courseList.isEmpty()){
//            Map<String,Object> result =  new HashMap<String, Object>();
//            result.put("error_code",1);
//            return result;
//        }
//
//        String courseId = courseList.get(0).getId();

        List<Checkin> checkins = checkinMapper.selectList(
                new QueryWrapper<Checkin>().in("course_id",courses)
                    .isNull("end_time")
        );

        if(checkins.isEmpty() || checkins.size() > 1){
            Map<String,Object> result =  new HashMap<String, Object>();
            result.put("error_code",1);
            return result;
        }

        Map<String,Object> result = new HashMap<>();
        result.put("checkin_id",checkins.get(0).getId());
        result.put("locate",checkins.get(0).getLocate());
        result.put("photo",checkins.get(0).getPhoto());
        result.put("start_time",checkins.get(0).getStartTime());
        result.put("teacher_id",checkins.get(0).getTeacherId());

        CheckinStudent checkinStudent = checkinStudentMapper.selectOne(new QueryWrapper<CheckinStudent>()
                .eq("checkin_id",checkins.get(0).getId())
                .eq("student_id",studentId)
        );

        if(checkinStudent!=null){
            result.put("error_code",2);
        }else{
            result.put("error_code",0);
        }

        return result;
    }

    @Override
    public OldResultVO submit(StudentSubmit studentSubmit) {
        //获取签到情况
        Checkin checkin = checkinMapper.selectById(studentSubmit.getCheckinId());

        if(checkin == null || checkin.getEndTime().getTime() < System.currentTimeMillis()/1000){
            return ResultVOUtil.oldError(20201); //签到不存在
        }

        if(checkin.getEndTime() != null){
            return ResultVOUtil.oldError(20203); //签到已关闭
        }

        CheckinStudent checkinStudent = checkinStudentMapper.selectOne(new QueryWrapper<CheckinStudent>()
                .eq("checkin_id",studentSubmit.getCheckinId())
                .eq("student_id",studentSubmit.getStudentId())
        );

        if(checkinStudent!=null || checkinStudent.getLeave() == "1"){
            return ResultVOUtil.oldError(10002); //已经签到或者标记缺勤
        }

        CheckinStudent newCheckinStudent = new CheckinStudent();

        newCheckinStudent.setCheckinId(Integer.valueOf(studentSubmit.getCheckinId()));
        newCheckinStudent.setCreateTime(new Timestamp(System.currentTimeMillis()));
        newCheckinStudent.setLatitude(studentSubmit.getLatitude().toString());
        newCheckinStudent.setLongitude(studentSubmit.getLongitude().toString());
        newCheckinStudent.setTimeStamp(studentSubmit.getTimestamp());
        newCheckinStudent.setLeave("0");
        newCheckinStudent.setStudentName(studentSubmit.getStudentName());
        newCheckinStudent.setStudentId(studentSubmit.getStudentId());

        int insert = checkinStudentMapper.insert(newCheckinStudent);
        if(insert != 1){
            return ResultVOUtil.oldError(20201);
        }

        if(checkin.getPhoto() == 1){ //异步处理人脸识别
            try {
                amqpTemplate.convertAndSend(
                        "checkinQueue",  //签到人脸检测队列
                        objectMapper.writeValueAsString(studentSubmit),
                        message -> {
                            message.getMessageProperties().setExpiration("5000"); //消息TTL 5s
                            return message;
                        });
            } catch (JsonProcessingException e) {
                logger.error(e.getMessage(),e);
            }
        }

        return ResultVOUtil.oldSuccess();
    }
}
